<template>
    <div>
        <el-row>
            <el-button type="primary" @click="addHandleClick">添加</el-button>
            <p/>
        </el-row>
        <!-- 数据列表表单区域 -->
        <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="id" label="ID"></el-table-column>
            <el-table-column prop="code" label="编号"></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="create_time" label="创建时间" :formatter="carTimeFilter"></el-table-column>
            <el-table-column fixed="right" label="操作" width="140">
                <template slot-scope="scope">
                    <el-button type="success" @click="editorHandleClick(scope.row)" size="mini"
                        icon="el-icon-edit"></el-button>
                    <el-button @click="deleteHandleClick(scope.row)" type="danger" size="mini"
                        icon="el-icon-delete"></el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 列表分页操作区域 -->
        <el-pagination :current-page="currentPage" :page-size="pageSize" @current-change="handleCurrentChange" background
            layout="prev, pager, next" :total="totalCount">
        </el-pagination>
        <!-- 编辑和添加页面定义 -->
        <el-dialog :title="isEditor ? '编辑' : '添加'" :visible.sync="dialogAddFormVisible">
            <el-form :model="dialogForm" :rules="rules" ref="dialogForm">
                <el-input type="hidden" v-model="dialogForm.id" autocomplete="off"></el-input>

                <el-form-item prop="code" label="编号" :label-width="dialogFormLabelWidth">
                    <el-input v-model="dialogForm.code" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item prop="name" label="名称" :label-width="dialogFormLabelWidth">
                    <el-input v-model="dialogForm.name" autocomplete="off"></el-input>
                </el-form-item>
              
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="resetDialogFormData('dialogForm')" v-if="!isEditor">重 置</el-button>
                <el-button @click="dialogAddFormVisible = false" v-if="isEditor">取 消</el-button>
                <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import moment from "moment";


export default {
    data() {
        return {
            searchDate: "",
            //数据分页
            currentPage: 1,//当前页码
            totalCount: 1,// 总条数，根据接口获取数据长度(注意：这里不能为空)
            pageSize: 10,//页面数据显示数量
            //数据列表表单
            tableData: [],//数据列表表单的数据域
            tableChecked: [],//批量删除时被选中行
            ids: [],//批量删除的id
            //数据更新
            updateUserId: 0,//编辑时要更新的用户id
            //搜索
            searchForm: {
               
            },
            isEditor: false,//标志弹出框是编辑还是添加
            dialogAddFormVisible: false,//编辑表单弹出框是否显示
            dialogForm: {//弹出框的数据域
                id: "",
                code: "",
                name: "",
            },
            dialogFormLabelWidth: '120px',//弹出表单的输入框的宽度
            urls: {
                update: "/api/category/updateById",
                save: "/api/category/add",
                search: "/api/category/list",
                delete: "",
                find: "/api/category/findById",
            },
        };
    },
    created: function () {
        this.pageList();

    },
    methods: {
        //加载列表数据
        pageList: function () {
            let url = this.$data.urls.search + "/" + this.currentPage + "/" + this.pageSize;
            this.$axios({
                method: "POST",
                url: url,
                data: this.$data.searchForm,
            }).then((res) => {
                let code = res.data.code;
                if (code == 0) {
                    this.$data.tableData = res.data.data.records;
                    this.$data.totalCount = res.data.data.total;
                    this.$data.currentPage = res.data.data.current;
                }
            }).catch((error) => {
                console.log(error);
            });
        },
        onSearch: function () {
            this.pageList();
        },
        resetSearchForm: function () {
            //重置表单数据
            this.searchDate = '';
            this.resetDialogFormData('searchForm')
            this.pageList();

        },
        //重置编辑弹出框表单的数据
        resetDialogFormData: function (formName) {
            
           this.dialogForm =  {
                id: "",
                code: "",
                name: "",
            }
        },
        addHandleClick: function () {
            this.resetDialogFormData('dialogForm');
            this.$data.isEditor = false;
            this.$data.dialogAddFormVisible = true;
        },
        saveOrUpdate: function (flag) {
            let url = this.$data.urls.save
            let method = 'POST'
            if(this.dialogForm.id > 0){
                url = this.$data.urls.update
                method = 'PUT'
            }
            this.$refs['dialogForm'].validate((valid) => {
                if (valid && this.checkDialogForm()) {
                    axios({
                        method: method,
                        url: url,
                        data: this.dialogForm
                    }).then(res => {
                        let code = res.data.code
                        if (code == 0) {
                            this.pageList();
                            this.$data.dialogAddFormVisible = false
                        } else {
                            this.$message.error('操作失败');
                        }
                    }).catch(error => {
                        console.log(error);
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        editorHandleClick: function (row) {
            let that = this
            this.isEditor = true;
            let url = this.$data.urls.find + "/" + row.id;
            axios({
                method: "GET",
                url: url,
                data: {},
            }).then((res) => {
                let code = res.data.code;
                if (code == 0) {
                    this.resetDialogFormData('dialogForm');
                    this.$nextTick(() => {
                        this.$data.dialogForm.id = res.data.data.id;
                        this.$data.dialogForm.code = res.data.data.code;
                        this.$data.dialogForm.name = res.data.data.name;
                    });
                    
                    this.dialogAddFormVisible = true;
                }
            }).catch((error) => {
                console.log(error)
            });
        },
        exportExcel: function () {
            let url = this.urls.exportExcel;
            axios({
                method: "GET",
                url: url,
                data: {},
            })
                .then((res) => {
                    let code = res.data.code;
                    if (code == 200) {
                        console.log(res.data.data);
                        window.location.href = process.env.VUE_APP_BASEURL + "/profile/download/" + res.data.data;
                    }
                })
                .catch((error) => {
                    console.log(error);
                });
        },
        deleteHandleClick: function (row) {
            this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$data.ids.push(row.id);
                this.delete();
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //删除ids中对应的
        delete: function () {
            let data = this.$data.ids
            //获得url尾部,要删除的id部分
            let urlChild = '';
            data.forEach((e) => {
                urlChild += 'ids=' + e + '&'
            });
            urlChild = urlChild.substring(0, urlChild.lastIndexOf('&'));

            let url = this.$data.urls.delete + '/?' + urlChild
            axios({
                method: 'GET',
                url: url,
                data: {}
            }).then(res => {
                let code = res.data.code;
                this.$data.ids = new Array();//清空要删除的id数组
                if (code == 200) {
                    this.pageList();
                }
            }).catch(error => {
                console.log(error);
            });
        },
        handleSelectionChange: function (val) {
            this.tableChecked = val;
        },
        batchDelete: function () {
            let that = this;
            let _rows = this.$data.tableChecked;
            if (_rows.length <= 0) {
                this.$message.warning('请先选择需要删除的数据');
                return;
            }
            that.$confirm('是否删除选中的所有用户?删除后无法恢复!', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                _rows.forEach(element => {
                    that.ids.push(element.id)
                })
                this.delete();
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleCurrentChange: function (val) {
            this.$data.currentPage = val;
            this.pageList();
        },
        checkDialogForm() {
            return true;
        },
        carTimeFilter: function (row, column, cellValue) {
            if (cellValue != null) {
                return moment(cellValue).format("YYYY-MM-DD HH:mm:ss");
            }
        },
        dateChange: function () {
            this.searchForm.createTimeBegin = this.searchDate[0];
            this.searchForm.createTimeEnd = this.searchDate[1];
            console.log(this.searchForm.createTimeBegin + " | " + this.searchForm.createTimeEnd)
        },
    },
};
</script>

<style></style>